package org.justframework.server;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

/**
 * 
 * path template in pattern format
 *
 */
public class PathPattern implements Comparable<Object>{
	
	/**
	 * initial path template
	 */
	private String path;
	
	/**
	 * path pattern in string format
	 */
	private String pattern;
	
	/**
	 * variable names in path pattern 
	 */
	private List<String> paramNames = new ArrayList<String>();
	
	public PathPattern(String path){
		this.path = path;
		parsePath();
	}
	
	/**
	 * parse path template
	 */
	private void parsePath(){
		//get parameter names from url
		StringTokenizer token = new StringTokenizer(path,"/");
		while(token.hasMoreTokens()){
			String dir = token.nextToken();
			if(dir.startsWith("{")){
				dir = dir.substring(1, dir.length()-1);
				paramNames.add(dir);
			}
		}
		this.pattern = path.replaceAll("\\{\\w+\\}", "(.*)");		
	}

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public String getPattern() {
		return pattern;
	}

	public void setUrlPattern(String pattern) {
		this.pattern = pattern;
	}

	public List<String> getParamNames() {
		return paramNames;
	}

	public void setParamNames(List<String> paramNames) {
		this.paramNames = paramNames;
	}

	/**
	 * calculate path depth, one '/' one depth
	 * @return
	 */
	private int getDepth() {
		int depth = 0;
		if(path != null){
			for(byte bt:path.getBytes()){
				if(bt == '/'){
					depth++;
				}
			}			
		}
		return depth;
	}	

	public int compareTo(Object o) {
		PathPattern up = (PathPattern)o;
		return Integer.valueOf(getDepth()).compareTo(Integer.valueOf(up.getDepth()));
	}
	
	@Override
	public boolean equals(Object o){
		if(o instanceof PathPattern){
			return path.equals(((PathPattern) o).path);
		}
		return false;
	}
	
	@Override
	public int hashCode(){
		return path.hashCode();
	}

}
